
package com.yimixian.app.address;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.yimixian.app.fragment.DialogFragment;
import com.yimixian.app.ui.dialog.WheelViewDialogNew;
import com.yimixian.app.util.StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.EventBusDomain.ShowAdSelectChange;
import com.yimixian.app.R;
import com.yimixian.app.activity.BaseNaviFragmentGroupActivity;
import com.yimixian.app.common.CacheKeys;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.SharePreferenceKeys;
import com.yimixian.app.common.StatConstants;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.location.CheckAddressInfoMapActivity;
import com.yimixian.app.location.LocatedListener;
import com.yimixian.app.location.LocationProvider;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.KV;
import com.yimixian.app.net.HttpApi;
import com.yimixian.app.rest.YmxDataService;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.ui.dialog.WheelViewDialog;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;

import de.greenrobot.event.EventBus;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ModifyOrCreateAddressActivity extends BaseNaviFragmentGroupActivity {

    public static final String EXTRA_ADDRESS_ID = "extra_address_id";
    public static final String ADDRESS_FOR_CONFIRM = "address_for_confirm";

    @InjectView(R.id.name_edit_text)
    EditText mNameEditText;
    @InjectView(R.id.phone_number_edit_text)
    EditText mPhoneNumberEditText;
    @InjectView(R.id.room_number_edit_text)
    EditText mRoomNumberEditText;
    @InjectView(R.id.tag_edit_text)
    EditText mTagEditText;
    @InjectView(R.id.confirm_button)
    TextView mSubmitButton;
    @InjectView(R.id.select_city_button)
    TextView mSelectCityButton;
    @InjectView(R.id.select_province_button)
    TextView selectProvinceButton;
    @InjectView(R.id.select_district_button)
    TextView selectDistrictButton;
    @InjectView(R.id.select_address_button)
    TextView mSelectAddressButton;
    @InjectView(R.id.et_address)
    EditText et_address;
    @InjectView(R.id.lady_text)
    TextView mLadyText;
    @InjectView(R.id.gentleman_text)
    TextView mGentlemanText;
    @InjectView(R.id.original_address)
    TextView mOriginalAddress;
    @InjectView(R.id.back_button)
    ImageView mBackButton;
    @InjectView(R.id.title_text)
    TextView mTitleText;
    @InjectView(R.id.delete_button)
    TextView mDeleteButton;
    @InjectView(R.id.district_line)
    View district_line;

    private YmxDataService mYmxDataService;
    private DataManager mDataManager;
    private MutableAddress mAddress;
    // private String[] mRegions;
//    private ProgressDialogFragment mProgressDialog;
    private boolean mShouldShowMap = true;
    private String locatedCity;
    private LatLng mLatLng;
    private String store_id;
    private Dialog mProgressDialog;
//    private ProgressDialogFragment dialog;
    private String provinceKey, cityKey, districtKey, province, city, district;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mYmxDataService = YmxDataService.getInstance();
        mDataManager = DataManager.getInstance();
        int addressId = getIntent().getIntExtra(EXTRA_ADDRESS_ID, 0);
        if (addressId > 0) {
            List<Address> addresses = SharedPreferencesHelper
                    .getAddresses(SharePreferenceKeys.ADDRESSES);
            if (addresses == null || addresses.size() == 0) {
                finish();
                return;
            }
            for (Address address : addresses) {
                if (address.id == addressId) {
                    mAddress = new MutableAddress(address);
                    break;
                }
            }
            if (mAddress == null) {
                finish();
                return;
            }
        }

        AppConfig config = mDataManager.get(CacheKeys.APP_CONFIG);
        // if(config != null && config.regions != null) {
        // mRegions = new String[config.regions.size()];
        // for (int i = 0; i < config.regions.size(); ++i) {
        // mRegions[i] = config.regions.get(i).name;
        // }
        // }

        setContentView(R.layout.modify_address_activity);
        ButterKnife.inject(this);
        AppConfig appConfig = mDataManager.get(CacheKeys.APP_CONFIG);
        if (appConfig != null) {
            mShouldShowMap = appConfig.shouldShowMap;
        }
        mSubmitButton.setText("保存");
        mTitleText.setText(mAddress == null ? "新建收货地址" : "修改收货地址");
        addTextWatchers();
        if (mAddress == null) {
            mDeleteButton.setVisibility(View.GONE);
        } else {
            mDeleteButton.setVisibility(View.VISIBLE);
        }
        mBackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UiUtils.closeSoftKeyBoard(ModifyOrCreateAddressActivity.this);
                finish();
            }
        });

        if (addressId > 0) {
            mDeleteButton.setVisibility(View.VISIBLE);
        }

        // address为空是新建收货地址
        if (mAddress == null) {
            mProgressDialog = UiUtils.showLoadingDialog(this, "定位中...");
            mAddress = new MutableAddress();
            selectGender("女士");
            // 判断是不是当前城市 不是 定位城市中心 是定位当前位置
            LocationProvider.getInstance().startBaiduLocated(false, new LocatedListener() {

                @Override
                public void locatedSuccessListener(BDLocation location) {
                    if (StringUtils.isNullOrEmpty(mAddress.city)) {
                        mAddress.city = city = location.getCity();
                        mAddress.province = province = location.getAddress().province;
                        mAddress.district = district = location.getDistrict();
                        mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                        locatedCity = location.getCity();
                        setRegion(mAddress.province, mAddress.city, district);
                        mSelectCityButton.setTextColor(0xff333333);
                        selectDistrictButton.setTextColor(0xff333333);
                        initJsonData();
                        if (!Strings.isNullOrEmpty(district)) {
                            district_line.setVisibility(View.VISIBLE);
                            selectDistrictButton.setVisibility(View.VISIBLE);
                        } else {
                            district_line.setVisibility(View.INVISIBLE);
                            selectDistrictButton.setVisibility(View.INVISIBLE);
                        }
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("province_key", provinceKey);
                        map.put("city_key", cityKey);
                        HttpApi.startPostRequest("/v3/users/current/addresses/is_area_location", map,
                                new HttpApi.RequestCallBack() {
                                    @Override
                                    public void requestSuccess(String result) {
                                        try {
                                            JSONObject json = new JSONObject(result);
                                            store_id = json.getString("store_id");
                                            //store_id有值手输，空地图选点
                                            if (StringUtils.isNullOrEmpty(store_id)) {
                                                mSelectAddressButton.setVisibility(View.VISIBLE);
                                                mSelectAddressButton.setEnabled(true);
                                                et_address.setVisibility(View.INVISIBLE);
                                                et_address.setText("");
                                                mAddress.poiAddress = null;
                                                mAddress.poiName = null;
                                            } else {
                                                mSelectAddressButton.setVisibility(View.INVISIBLE);
                                                et_address.setVisibility(View.VISIBLE);
                                                et_address.setEnabled(true);
                                                et_address.setText("");
                                                mAddress.poiAddress = null;
                                                mAddress.poiName = null;
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void requestError() {
                                    }

                                    @Override
                                    public void alwaysDo() {
                                        try {
                                            if (mProgressDialog != null) {
                                                mProgressDialog.dismiss();
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                });
                    }
                }

                @Override
                public void locatedSuccessGeoPoiInfoListener(PoiInfo poiInfo) {

                }

                @Override
                public void locatedFailedListener() {
                }

                @Override
                public void locatedFailedGeoPoiInfoListener() {

                }
            });
            return;
        }

        mNameEditText.setText(mAddress.name);
        mNameEditText.setSelection(mAddress.name.length());
        mPhoneNumberEditText.setText(mAddress.tel);
        mTagEditText.setText(mAddress.tag);

        if (mAddress.id > 0) {
            this.province = mAddress.province;
            this.city = mAddress.city;
            this.district = mAddress.district;
            initJsonData();
            if (!Strings.isNullOrEmpty(district)) {
                district_line.setVisibility(View.VISIBLE);
                selectDistrictButton.setVisibility(View.VISIBLE);
            } else {
                district_line.setVisibility(View.INVISIBLE);
                selectDistrictButton.setVisibility(View.INVISIBLE);
            }
            String province = config.getProviceName(mAddress.city);
            if (!Strings.isNullOrEmpty(province)) {
                selectProvinceButton.setTextColor(0xff333333);
                selectProvinceButton.setText(province);
                mAddress.province = province;
            }
            district = mAddress.district;
            store_id = mAddress.storeId;
            if (!Strings.isNullOrEmpty(district)) {
                selectDistrictButton.setTextColor(0xff333333);
                selectDistrictButton.setText(district);
            }
            if("-1".equals(mAddress.latitude) && "-1".equals(mAddress.longitude)){
                if (!Strings.isNullOrEmpty(mAddress.poiAddress)) {
                    et_address.setText(mAddress.poiAddress);
                    et_address.setVisibility(View.VISIBLE);
                    et_address.setEnabled(true);
                    mSelectAddressButton.setVisibility(View.INVISIBLE);
                    district_line.setVisibility(View.INVISIBLE);
                    selectDistrictButton.setVisibility(View.INVISIBLE);
                }
            }else{
                if (!Strings.isNullOrEmpty(mAddress.poiName)) {
                    mSelectAddressButton.setText(mAddress.poiName);
                    mSelectAddressButton.setVisibility(View.VISIBLE);
                    mSelectAddressButton.setEnabled(true);
                    district_line.setVisibility(View.VISIBLE);
                    selectDistrictButton.setVisibility(View.VISIBLE);
                    et_address.setVisibility(View.INVISIBLE);
                }
            }
            if (!Strings.isNullOrEmpty(mAddress.roomNo)) {
                mRoomNumberEditText.setText(mAddress.roomNo);
            }
            if (!Strings.isNullOrEmpty(mAddress.city)) {
                mSelectCityButton.setTextColor(0xff333333);
                mSelectCityButton.setText(mAddress.city);
            }
            if (!Strings.isNullOrEmpty(mAddress.district)) {
                selectDistrictButton.setTextColor(0xff333333);
                selectDistrictButton.setText(mAddress.district);
                district_line.setVisibility(View.VISIBLE);
                selectDistrictButton.setVisibility(View.VISIBLE);
            }else{
                district_line.setVisibility(View.INVISIBLE);
                selectDistrictButton.setVisibility(View.INVISIBLE);
            }
            if (!Strings.isNullOrEmpty(mAddress.poiName)) {
                mSelectAddressButton.setTextColor(0xff333333);
            }

            if (Strings.isNullOrEmpty(mAddress.poiName)) {
                mOriginalAddress.setText("原地址: " + mAddress.address);
                mOriginalAddress.setVisibility(View.VISIBLE);
            } else {
                mOriginalAddress.setVisibility(View.GONE);
            }
        }

        if (!"女士".equals(mAddress.gender) && !"先生".equals(mAddress.gender)) {
            mAddress.gender = "女士";
        }

        selectGender(mAddress.gender);

    }

    private void selectGender(String gender) {
        mAddress.gender = gender;
        Drawable checkedDrawable = getResources().getDrawable(R.drawable.checked_icon);
        Drawable uncheckedDrawable = getResources().getDrawable(R.drawable.unchecked_icon);
        int size = getResources().getDimensionPixelSize(R.dimen.checked_icon_size);
        checkedDrawable.setBounds(0, 0, size, size);
        uncheckedDrawable.setBounds(0, 0, size, size);
        if ("先生".equals(gender)) {
            MobclickAgent.onEvent(this, StatConstants.EDIT_ADDRESS_GENDER_MALE_CLICK);
            mGentlemanText.setCompoundDrawables(checkedDrawable, null, null, null);
            mLadyText.setCompoundDrawables(uncheckedDrawable, null, null, null);
        } else {
            MobclickAgent.onEvent(this, StatConstants.EDIT_ADDRESS_GENDER_FEMALE_CLICK);
            mGentlemanText.setCompoundDrawables(uncheckedDrawable, null, null, null);
            mLadyText.setCompoundDrawables(checkedDrawable, null, null, null);
        }
    }

    private void setRegion(String province, String city, String district) {
        if (Strings.isNullOrEmpty(province)) {
            selectProvinceButton.setText(getString(R.string.address_province_text));
            selectProvinceButton.setTextColor(0xffd0d0d0);
        } else {
            selectProvinceButton.setText(province);
            selectProvinceButton.setTextColor(0xff333333);
        }
        if (Strings.isNullOrEmpty(city)) {
            mAddress.city = null;
            mAddress.latitude = "";
            mAddress.longitude = "";
            mSelectCityButton.setText(getString(R.string.choose_city));
            mSelectCityButton.setTextColor(0xffd0d0d0);
        } else {
            mAddress.city = city;
            if (!StringUtils.isNullOrEmpty(locatedCity) && locatedCity.equals(city)) {
                mAddress.latitude = String.valueOf(mLatLng.latitude);
                mAddress.longitude = String.valueOf(mLatLng.longitude);
            } else {
                mAddress.latitude = "";
                mAddress.longitude = "";
            }
            mSelectCityButton.setText(city);
            mSelectCityButton.setTextColor(0xff333333);
            mAddress.poiName = null;
//            mSelectAddressButton.setText("详细地址");
//            mSelectAddressButton.setTextColor(0xffd0d0d0);
        }
        if(Strings.isNullOrEmpty(district)){
            selectDistrictButton.setText("选择区");
//            mSelectAddressButton.setTextColor(0xffd0d0d0);
        }else{
            selectDistrictButton.setText(district);
//            mSelectAddressButton.setTextColor(0xff333333);
        }
    }

    private void setAddress(MutableAddress address) {
        if(mSelectAddressButton.getVisibility() == View.VISIBLE){
            if (address == null || StringUtils.isNullOrEmpty(address.poiName)) {
                mAddress.poiName = null;
//                mSelectAddressButton.setText("详细地址");
//                mSelectAddressButton.setTextColor(0xffd0d0d0);
            } else {
                this.mAddress = address;
                mSelectAddressButton.setText(address.poiName);
                mSelectAddressButton.setTextColor(0xff333333);
            }
        }else{

        }
    }

    private void startPickingAddress() {
        Intent intent = new Intent(this, CheckAddressInfoMapActivity.class);
        intent.putExtra(CheckAddressInfoMapActivity.EXTRA_MUTABLE_ADDRESS, mAddress);
        startActivityForResult(intent, Constants.SEARCH_POI_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Constants.SEARCH_POI_REQUEST_CODE && resultCode == RESULT_OK) {
            mAddress = data.getParcelableExtra(CheckAddressInfoMapActivity.EXTRA_MUTABLE_ADDRESS);
            mAddress.poiId = "bd-" + mAddress.poiId;
            setAddress(mAddress);
        }
    }

    @OnClick({
            R.id.lady_text, R.id.gentleman_text
    })
    public void onGenderIconClicked(TextView textView) {
        selectGender(textView.getText().toString());
    }

    // private void showCityPickingDialog(final Runnable runnable) {
    // new AlertDialog.Builder(this)
    // .setTitle(getString(R.string.choose_city))
    // .setItems(
    // mRegions,
    // new DialogInterface.OnClickListener() {
    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // setCity(mRegions[which]);
    // if (runnable != null) {
    // runnable.run();
    // }
    // }
    // })
    // .show();
    // }

    private List<Map<String, Object>> provinceListMap;

    @OnClick({
//            R.id.select_city_button, R.id.select_province_button, R.id.select_district_button
            R.id.ll_choose
    })
    public void onSelectCityButtonClicked(View view) {
        MobclickAgent.onEvent(this, StatConstants.EDIT_ADDRESS_SELECT_CITY_CLICK);
        // showCityPickingDialog(null);
        AppConfig appConfig = DataManager.getInstance().get(CacheKeys.APP_CONFIG);
        if (appConfig.regions.size() <= 0)
            return;

        WheelViewDialogNew dialogNew = new WheelViewDialogNew(this, new String[]{mAddress.province, mAddress.city, mAddress.district}, provinceListMap);
        dialogNew.show();

        dialogNew.setClickSureListener(new WheelViewDialogNew.ClickSureListener() {
            @Override
            public void onSelected(List<Map<String, Object>> dataList) {
                String province = "", provinceKey = "";
                String city = "", cityKey = "";
                String district = "", districtKey = "";
                for (int i = 0; i < dataList.size(); i++) {
                    Map<String, Object> newMap = dataList.get(i);
                    if (newMap == null)
                        continue;
                    String key = (String) newMap.get("key");
                    String name = (String) newMap.get("name");
                    if (i == 0) {
                        provinceKey = key;
                        province = name;
                    } else if (i == 1) {
                        cityKey = key;
                        city = name;
                    } else if (i == 2) {
                        districtKey = key;
                        district = name;
                    }
                }

                if (Strings.isNullOrEmpty(district)) {
                    district_line.setVisibility(View.INVISIBLE);
                    selectDistrictButton.setVisibility(View.INVISIBLE);
                } else {
                    district_line.setVisibility(View.VISIBLE);
                    selectDistrictButton.setVisibility(View.VISIBLE);
                    selectDistrictButton.setTextColor(0xff333333);
                }

                if (!StringUtils.isNullOrEmpty(city) && mAddress != null) {
                    mAddress.province = province;
                    mAddress.provinceKey = provinceKey;
                    mAddress.city = city;
                    mAddress.cityKey = cityKey;
                    mAddress.district = district;
                    mAddress.districtKey = districtKey;
                    mAddress.latitude = "";
                    mAddress.longitude = "";
                    setRegion(province, city, district);
                    final Dialog dialogLoading = UiUtils.showLoadingDialog(ModifyOrCreateAddressActivity.this, "");
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("province_key", provinceKey);
                    map.put("city_key", cityKey);
                    HttpApi.startPostRequest("/v3/users/current/addresses/is_area_location", map,
                            new HttpApi.RequestCallBack() {
                                @Override
                                public void requestSuccess(String result) {
                                    try {
                                        if (dialogLoading != null) {
                                            dialogLoading.dismiss();
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    try {
                                        JSONObject json = new JSONObject(result);
                                        store_id = json.getString("store_id");
                                        //store_id有值手输，空地图选点
                                        if (StringUtils.isNullOrEmpty(store_id)) {
                                            mSelectAddressButton.setVisibility(View.VISIBLE);
                                            mSelectAddressButton.setEnabled(true);
                                            mSelectAddressButton.setText("点击选择详细地址");
//                                            district_line.setVisibility(View.INVISIBLE);
//                                            selectDistrictButton.setVisibility(View.INVISIBLE);
                                            et_address.setVisibility(View.INVISIBLE);
                                            et_address.setText("");
                                            mAddress.poiAddress = null;
                                            mAddress.poiName = null;
                                        } else {
                                            mSelectAddressButton.setVisibility(View.INVISIBLE);
//                                            district_line.setVisibility(View.VISIBLE);
//                                            selectDistrictButton.setVisibility(View.INVISIBLE);
                                            et_address.setVisibility(View.VISIBLE);
                                            et_address.setEnabled(true);
                                            et_address.setText("");
                                            mAddress.poiAddress = null;
                                            mAddress.poiName = null;
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void requestError() {
                                }

                                @Override
                                public void alwaysDo() {
                                }

                            });
                }

            }
        });

    }

    @OnClick({
            R.id.select_address_button
    })
    public void onSelectAddressButtonClicked(TextView textView) {
        // MobclickAgent.onEvent(this,
        // StatConstants.EDIT_ADDRESS_SELECT_DETAIL_ADDRESS_CLICK);
        // if
        // (mSelectCityButton.getText().equals(getString(R.string.choose_city)))
        // {
        // showCityPickingDialog(new Runnable() {
        // @Override
        // public void run() {
        // startPickingAddress();
        // }
        // });
        // } else {
        startPickingAddress();
        // }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @OnClick({
            R.id.tag_down_arrow
    })
    public void onTagDownArrowClicked(ImageView imageView) {
        MobclickAgent.onEvent(this, StatConstants.EDIT_ADDRESS_SELECT_TAG_CLICK);
        final String[] tags = new String[] {
                "单位", "家", "学校", "其它"
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle("选择标签")
                .setItems(
                        tags,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mTagEditText.setText(tags[which]);
                                mAddress.tag = tags[which];
                                switch (which) {
                                    case 0:
                                        MobclickAgent
                                                .onEvent(
                                                        ModifyOrCreateAddressActivity.this,
                                                        StatConstants.EDIT_ADDRESS_SELECT_TAG_COMPANY_CLICK);
                                        break;
                                    case 1:
                                        MobclickAgent.onEvent(ModifyOrCreateAddressActivity.this,
                                                StatConstants.EDIT_ADDRESS_SELECT_TAG_HOME_CLICK);
                                        break;
                                    case 2:
                                        MobclickAgent.onEvent(ModifyOrCreateAddressActivity.this,
                                                StatConstants.EDIT_ADDRESS_SELECT_TAG_SCHOOL_CLICK);
                                        break;
                                    case 3:
                                        MobclickAgent.onEvent(ModifyOrCreateAddressActivity.this,
                                                StatConstants.EDIT_ADDRESS_SELECT_TAG_OTHER_CLICK);
                                        break;
                                }
                            }
                        });
        UiUtils.showAlertDialog(builder);
    }

    @OnClick({
            R.id.confirm_button
    })
    public void onSubmitButtonClicked(TextView textView) {
        if (Strings.isNullOrEmpty(mAddress.name)) {
            UiUtils.showToast(this, "请输入收货人姓名");
            return;
        } else if (Strings.isNullOrEmpty(mAddress.tel)) {
            UiUtils.showToast(this, "请输入联系电话");
            return;
        } else if (!(mAddress.tel).startsWith("1") || mAddress.tel.length() != 11) {
            UiUtils.showToast(this, "手机号输入有误");
            return;
        } else if (Strings.isNullOrEmpty(mAddress.city)) {
            UiUtils.showToast(this, "请选择所在城市");
            return;
        } else if (Strings.isNullOrEmpty(mAddress.poiName) && mSelectAddressButton.getVisibility() == View.VISIBLE) {
            UiUtils.showToast(this, "请选择详细地址");
            return;
        } else if (Strings.isNullOrEmpty(mAddress.poiAddress) && et_address.getVisibility() == View.VISIBLE) {
            UiUtils.showToast(this, "请填写详细地址");
            return;
        } else if (Strings.isNullOrEmpty(mAddress.roomNo)) {
            UiUtils.showToast(this, "请输入门牌号");
            return;
        }
        MobclickAgent.onEvent(this, StatConstants.EDIT_ADDRESS_CONFIRM_CLICK);
        // if (mShouldShowMap) {
        // Intent intent = new Intent(ModifyOrCreateAddressActivity.this,
        // CheckAddressInfoMapActivity.class);
        // intent.putExtra(ADDRESS_FOR_CONFIRM, mAddress);
        // startActivityForResult(intent,
        // Constants.LOCATION_CONFIRM_REQUEST_CODE);
        // } else {
        createOrModifyAddress();
        // }
    }

    private void createOrModifyAddress() {
        mSubmitButton.setEnabled(false);
        mDeleteButton.setEnabled(false);
        mProgressDialog = UiUtils.showLoadingDialog(this, "保存地址...");

        if(Strings.isNullOrEmpty(mAddress.provinceKey))
            mAddress.provinceKey = provinceKey;
        if(Strings.isNullOrEmpty(mAddress.cityKey))
            mAddress.cityKey = cityKey;
        if(Strings.isNullOrEmpty(mAddress.districtKey))
            mAddress.districtKey = districtKey;

        if (mAddress.id > 0) {
            if(mSelectAddressButton.getVisibility() == View.VISIBLE){
                mYmxDataService.updateAddress(mAddress)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                new Action1<Boolean>() {
                                    @Override
                                    public void call(Boolean aBoolean) {
                                        refetchAddresses(getResources().getString(
                                                R.string.address_update_success), true);
                                    }
                                },
                                new Action1<Throwable>() {
                                    @Override
                                    public void call(Throwable throwable) {
                                        if(mProgressDialog != null){
                                            mProgressDialog.dismiss();
//                                            mProgressDialog = UiUtils.dismiss(mProgressDialog);
                                        }
                                        mSubmitButton.setEnabled(true);
                                        mDeleteButton.setEnabled(true);
                                        UiUtils.toastError(ModifyOrCreateAddressActivity.this,
                                                throwable);
                                    }
                                }
                        );
            }else{
                Map<String, String> map = new HashMap<>();
                map.put("store_id", store_id);
                map.put("name", mAddress.name);
                map.put("gender", mAddress.gender);
                map.put("tel", mAddress.tel);
                map.put("province", mAddress.province);
                map.put("city", mAddress.city);
                map.put("district", mAddress.district);
                map.put("poi_address", mAddress.poiAddress);
                map.put("room_no", mAddress.roomNo);
                map.put("tag", mAddress.tag);
                HttpApi.startPostRequest("/v3/users/current/addresses/" + mAddress.id +"/update_area_location", map, new HttpApi.RequestCallBack() {
                    @Override
                    public void requestSuccess(String result) {
                        try {
                            JSONObject json = new JSONObject(result);
                            if(json.has("error")){
                                UiUtils.showToast(json.getJSONObject("error").getString("message"));
                                return;
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        refetchAddresses(getResources().getString(
                                R.string.address_build_success), true);
                    }

                    @Override
                    public void requestError() {
                        UiUtils.showToast("服务器连接异常");
                    }

                    @Override
                    public void alwaysDo() {
                        if(mProgressDialog != null){
                            mProgressDialog.dismiss();
                        }
                        mSubmitButton.setEnabled(true);
                        mDeleteButton.setEnabled(true);
                    }
                });
            }
        } else {
            if(mSelectAddressButton.getVisibility() == View.VISIBLE){
                mYmxDataService.createAddress(mAddress)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                new Action1<Address>() {
                                    @Override
                                    public void call(Address address) {
                                        mAddress = new MutableAddress(address);
                                        refetchAddresses(getResources().getString(
                                                R.string.address_build_success), true);
                                    }
                                },
                                new Action1<Throwable>() {
                                    @Override
                                    public void call(Throwable throwable) {

                                        if(mProgressDialog != null){
                                            mProgressDialog.dismiss();
                                        }
                                        mSubmitButton.setEnabled(true);
                                        mDeleteButton.setEnabled(true);
                                        UiUtils.toastError(ModifyOrCreateAddressActivity.this,
                                                throwable);
                                    }
                                }
                        );
            }else{

                Map<String, String> map = new HashMap<>();
                map.put("store_id", store_id);
                map.put("name", mAddress.name);
                map.put("gender", mAddress.gender);
                map.put("tel", mAddress.tel);
                map.put("province", mAddress.province);
                map.put("city", mAddress.city);
                map.put("district", district);
                map.put("poi_address", mAddress.poiAddress);
                map.put("room_no", mAddress.roomNo);
                map.put("tag", mAddress.tag);
                HttpApi.startPostRequest("/v3/users/current/addresses/create_area_location", map, new HttpApi.RequestCallBack() {
                    @Override
                    public void requestSuccess(String result) {
                        try {
                            JSONObject json = new JSONObject(result);
                            if(json.has("error")){
                                UiUtils.showToast(json.getJSONObject("error").getString("message"));
                            }else{
                                json = json.optJSONObject("address");
                                Address address = new Address();
                                address.address = json.optString("address");
                                address.city = json.optString("city");
                                address.district = json.optString("district");
                                address.id = json.optInt("id");
                                address.latitude = json.optString("latitude");
                                address.longitude = json.optString("longitude");
                                address.name = json.optString("name");
                                address.poiAddress = json.optString("poi_address");
                                address.poiId = json.optString("poi_id");
                                address.poiName = json.optString("poi_name");
                                address.province = json.optString("province");
                                address.roomNo = json.optString("room_no");
                                address.storeId = json.optString("store_id");
                                address.tag = json.optString("tag");
                                address.tel = json.optString("tel");
                                mAddress = new MutableAddress(address);
                                refetchAddresses(getResources().getString(
                                        R.string.address_build_success), true);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void requestError() {
                        UiUtils.showToast("服务器连接异常");
                    }

                    @Override
                    public void alwaysDo() {
                        if(mProgressDialog != null){
                            mProgressDialog.dismiss();
                        }
                        mSubmitButton.setEnabled(true);
                        mDeleteButton.setEnabled(true);
                    }
                });
            }
        }
    }

    @OnClick({
            R.id.delete_button
    })
    public void onDeleteButtonClicked(TextView imageView) {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        deleteAddress();
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        break;
                }
            }
        };
        AlertDialog.Builder builder =new AlertDialog.Builder(this)
                .setMessage("确定要删除这个地址？")
                .setPositiveButton(getString(R.string.confirm), dialogClickListener)
                .setNegativeButton(getString(R.string.cancel), dialogClickListener);
        UiUtils.showAlertDialog(builder);
    }

    private void deleteAddress() {
        MobclickAgent.onEvent(this, StatConstants.EDIT_ADDRESS_DELETE_CLICK);
        mSubmitButton.setEnabled(false);
        mDeleteButton.setEnabled(false);
        mProgressDialog = UiUtils.showLoadingDialog(this, "删除地址...");
        mYmxDataService.deleteAddress(mAddress.id)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                refetchAddresses("成功删除地址", false);
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                if(mProgressDialog != null){
                                    mProgressDialog.dismiss();
                                }
                                mSubmitButton.setEnabled(true);
                                mDeleteButton.setEnabled(true);
                                UiUtils.toastError(ModifyOrCreateAddressActivity.this, throwable);
                            }
                        }
                );
    }

    private void refetchAddresses(final String toastText, final boolean isSaveAddress) {
        mYmxDataService.getAddresses(false)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<List<Address>>() {
                            @Override
                            public void call(List<Address> addresses) {
                                sortOutAllAddresses(addresses, isSaveAddress);
                                UiUtils.showToast(ModifyOrCreateAddressActivity.this, toastText);
                                if(mProgressDialog != null){
                                    mProgressDialog.dismiss();
                                }
                                if (isSaveAddress) {
                                    setResult(RESULT_OK);
                                }
                                finish();
                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                if(mProgressDialog != null){
                                    mProgressDialog.dismiss();
                                }
                                finish();
                            }
                        }
                );
    }

    private void sortOutAllAddresses(List<Address> addresses, boolean isSaveAddress) {
        SharedPreferencesHelper.saveAddresses((ArrayList) addresses, SharePreferenceKeys.ADDRESSES);
        if (isSaveAddress) {
            SharedPreferencesHelper.saveAddress(new Address(mAddress),
                    SharePreferenceKeys.CURRENT_ADDRESS);
        } else {
            Address currentAddress = SharedPreferencesHelper
                    .getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
            if (currentAddress == null)
                return;
            int addressId = mAddress.id;
            if (addressId != 0 && addressId == currentAddress.id) {
                SharedPreferencesHelper.clearAddress(SharePreferenceKeys.CURRENT_ADDRESS);
                EventBus.getDefault().post(new ShowAdSelectChange());
            }
        }

    }

    private void addTextWatchers() {
        mNameEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAddress.name = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mPhoneNumberEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAddress.tel = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mRoomNumberEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAddress.roomNo = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        mTagEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mAddress.tag = s.toString();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        et_address.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mAddress.poiName = mAddress.poiAddress = s.toString();
            }
        });
    }

    private void initJsonData(){
//        if(provinceListMap == null){
            provinceListMap = new ArrayList<>();
            List<Map<String, Object>> cityListMap = new ArrayList<>();
            List<Map<String, Object>> districtListMap = new ArrayList<>();

            String data = SharedPreferencesHelper.getString(Constants.REGION_DATA);

            try {
                JSONObject json = new JSONObject(data);
                JSONArray province = json.optJSONArray("regions");
                for (int i = 0; i < province.length(); i++) {
                    JSONObject eachProvince = province.getJSONObject(i);
                    Map<String, Object> mapProvince = new HashMap<>();
                    mapProvince.put("id", eachProvince.optString("id"));
                    mapProvince.put("key", eachProvince.optString("key"));
                    mapProvince.put("name", eachProvince.optString("name"));
                    if(eachProvince.optString("name").equals(this.province)){
                        provinceKey = eachProvince.optString("key");
                    }
                    JSONArray city = eachProvince.optJSONArray("cities");
                    cityListMap = new ArrayList<>();
                    if(city != null){
                        for (int j = 0; j < city.length(); j++) {
                            JSONObject eachCity = city.getJSONObject(j);
                            Map<String, Object> mapCity = new HashMap<>();
                            mapCity.put("id", eachCity.optString("id"));
                            mapCity.put("key", eachCity.optString("key"));
                            mapCity.put("name", eachCity.optString("name"));
                            if(eachCity.optString("name").equals(this.city)){
                                cityKey = eachCity.optString("key");
                            }
                            JSONArray district = eachCity.optJSONArray("districts");
                            districtListMap = new ArrayList<>();
                            if(district != null){
                                for (int k = 0; k < district.length(); k++) {
                                    JSONObject eachDistrict = district.getJSONObject(k);
                                    Map<String, Object> mapDistrict = new HashMap<>();
                                    mapDistrict.put("id", eachDistrict.optString("id"));
                                    mapDistrict.put("key", eachDistrict.optString("key"));
                                    mapDistrict.put("name", eachDistrict.optString("name"));
                                    if(eachDistrict.optString("name").equals(this.district)){
                                        districtKey = eachDistrict.optString("key");
                                    }
                                    districtListMap.add(mapDistrict);
                                }
                            }
                            mapCity.put("nextData", districtListMap);
                            cityListMap.add(mapCity);
                        }
                    }
                    mapProvince.put("nextData", cityListMap);
                    provinceListMap.add(mapProvince);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

//        }
    }

}
